<?php
function postCurl($url, $body = array(), $header = array(), $method = 'POST')
{
    array_push($header, 'Accept: application/json');
    array_push($header, 'Content-Length: ' . strlen(http_build_query($body)));
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    switch ($method) {
        case 'GET':
            curl_setopt($ch, CURLOPT_HTTPGET, true);
            break;
        case 'POST':
            curl_setopt($ch, CURLOPT_POST, true);
            break;
        case 'PUT':
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            break;
        case 'DELETE':
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
            break;
    }

    curl_setopt($ch, CURLOPT_USERAGENT, 'SSTS Browser/1.0');
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);  //原先是FALSE，可改为2

    if ($body) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($body));
    }
    if ($header) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }

    $ret = curl_exec($ch);
    curl_close($ch);
    return $ret;
}
function create_uuid($prefix = ""){
    $str = md5(uniqid(mt_rand(), true));
    $uuid = substr($str,0,8).'-';
    $uuid .= substr($str,8,4) . '-';
    $uuid .= substr($str,12,4) . '-';
    $uuid .= substr($str,16,4) . '-';
    $uuid .= substr($str,20,12);
    return $prefix . $uuid;
}


function thumbex($src, $index = 0) {
    if (!$src) {
        $path = "images/noimg.gif";
    } else {
        $path = preg_replace('/(.+)\/(\d+)\.(jpg|jpeg|png|gif)/', "\\1/thumbs/\\2_t{$index}.jpg", $src);
    }
    return IMG_URL.$path;
}

/* * 格式化输出信息* */
if (!function_exists('prf')) {

    function prf($data) {
        echo '<br/><pre>';
        print_r($data);
        echo '</pre><br/>';
        echo '<hr color="';
        if (function_exists('rndcolor')) {
            echo rndcolor();
        } else {
            echo '#ccc';
        }
        echo '"/>';
    }

}

/**
 * 说明：处理数组中的特殊字符，将HTML的特殊字符处理成PHP的安全字符,返回处理过的数组
 * 参数：数组$arr
 */
function set_htmlspecialchars(& $arr) {
    if (!isset($arr))
        return null;
    if (is_array($arr)) {
        foreach ($arr as $key => & $row) {
            $arr [$key] = set_htmlspecialchars($arr [$key]);
        }
    } else {
        if (is_string($arr)) {
            $arr = htmlspecialchars(trim($arr), ENT_QUOTES);
        }
    }
    return $arr;
}

/**
 * 说明：HTML实体转换为HTML字符
 * 参数：数组$arr
 * */
function set_htmlspecialchars_decode(& $arr) {
    if (!isset($arr))
        return null;
    if (is_array($arr)) {
        foreach ($arr as $key => & $row) {
            $arr [$key] = set_htmlspecialchars_decode($arr [$key]);
        }
    } else {
        if (is_string($arr)) {
            $arr = htmlspecialchars_decode(trim($arr));
        }
    }
    return $arr;
}

/*
 * 判断是否为空，空则返回默认值
 */

function def($data, $default = '') {
    if (isset($data)) {
        return $data;
    } else {
        return $default;
    }
}

/*
 * 错误处理方法
 */

function errorFunction($error) {
    if (YII_DEBUG) {
        var_dump($error);
    } else {

    }
}

/*
 * 检测特殊字符的方法
 */

function checkValid($string) {
    if (preg_match("/['.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $string)) {
        return true;
    } else {
        return false;
    }
}


/**
 * void makedir ($path)
 * 创建多级目录
 * @param $path 要创建的目录完整路径
 */
function makedir($path) {
    $s = preg_split('/\\\\|\//', $path, -1, PREG_SPLIT_NO_EMPTY);
    $p = "";
    do {
        $c = array_shift($s);
        if (DIRECTORY_SEPARATOR != '\\') {
            $p .= '/' . $c;
        } else {
            $p .= $c . '/';
        }
        if (!file_exists($p)) {
            mkdir($p);
            chmod($p, 0777);
        }
    } while ($s);
}

/**
 * 截取字符 if > $len ... else 空白    多添加一个字段$string   作为截取后追加字段可不填写
 */
function cut_str($str, $len = 20, $strip_tags = false, $string = '') {
    if ($strip_tags) {
        $str = strip_tags($str);
        $pattern = array('/\&nbsp;/', '/ {2,}/', '/\s{2,}/');
        $str = preg_replace($pattern, '', $str);
    }

    if (mb_strlen($str, 'utf-8') > $len) {
        return mb_substr($str, 0, $len, "utf-8") . $string;
    } else {
        return $str;
    }
}


/*
 * 设置默认值
 */

function setDefault($data, $key, $default = '') {
    if (isset($data)) {
        if (is_object($data) && isset($data->$key)) {
            if($data->$key){
                return $data->$key;
            }
        }
        if (is_array($data) && isset($data[$key])) {
            if($data[$key]){
                return $data[$key];
            }
        }
        if (is_bool($data) || is_string($data) || is_int($data)) {
            if ($data) {
                return $data;
            }
        }
        return $default;
    } else {
        return $default;
    }
}

/*
 * formatUrl($oldUrl=array(),$addQuery=array())
 * $oldUrl		旧的地址参数
 * $addQuery	追加的参数
 */

function formatUrl($oldUrl = array(), $addQuery = array()) {

    $oldUrl = array_merge($oldUrl, $addQuery);
    if (empty($oldUrl) && !is_array($oldUrl)) {
        return '';
    }
    $url = '?';
    $i = 1;
    foreach ($oldUrl as $kk => $vv) {
        $url = ($i == 1) ? $url . $kk . '=' . $vv : $url . '&' . $kk . '=' . $vv;
        ;
        $i++;
    }
    return $url;
}
/**
 * 去除所有的标签空格方式
 * */
function passString($string) {
    $re = '';
    $re = strip_tags($string); //去除HTML标签
    $re = preg_replace("/[\s]{2,}/", "", $re);

    //定义替换数组
    $qian = array("&nbsp;", " ");
    $hou = array("", "");
    $re = str_replace($qian, $hou, $re);
    return $re;
}


//过滤站外链接
function Filterlink($string) {
    $preg = '/<a(?:\s|\s[^>]+)*\shref=\"(?!\w+:\/\/(\w+\.)*csc86\.com[\"\?\/\#]|[\"\?\/\#])[^>]*>/i';
    return preg_replace($preg, "", $string);
}


/**
 *  页面参数配置
 * */
function cscpages($count) {
    $page = Yii::app()->request->getQuery('page', 0);
    $limit = Yii::app()->request->getQuery('limit', 10);
    $arr = array();
    if (!$page || !is_numeric($page))
        $page = 0;
    if (!$limit || !is_numeric($limit))
        $limit = 10;
    if ($page >= 1) {
        $page = $page - 1;
    }
    if ($count > $limit) {
        $total = ceil($count / $limit) - 1;
        if ($page >= $total) {
            $page = $total;
        }
        $arr['start'] = $page * $limit;
        $arr['size'] = $limit;
    } else {
        $arr['start'] = 0;
        $arr['size'] = $limit;
    }
    return $arr;
}

//发布外部方法
function ecm_json_encode($value) {
    $props = '';
    if (is_object($value)) {
        foreach (get_object_vars($value) as $name => $propValue) {
            if (isset($propValue)) {
                $props .= $props ? ',' . ecm_json_encode($name) : ecm_json_encode($name);
                $props .= ':' . ecm_json_encode($propValue);
            }
        }
        return '{' . $props . '}';
    } elseif (is_array($value)) {
        $keys = array_keys($value);
        if (!empty($value) && !empty($value) && ($keys[0] != '0' || $keys != range(0, count($value) - 1))) {
            foreach ($value as $key => $val) {
                $key = (string) $key;
                $props .= $props ? ',' . ecm_json_encode($key) : ecm_json_encode($key);
                $props .= ':' . ecm_json_encode($val);
            }
            return '{' . $props . '}';
        } else {
            $length = count($value);
            for ($i = 0; $i < $length; $i++) {
                $props .= ($props != '') ? ',' . ecm_json_encode($value[$i]) : ecm_json_encode($value[$i]);
            }
            return '[' . $props . ']';
        }
    } elseif (is_string($value)) {
        //$value = stripslashes($value);
        $replace = array('\\' => '\\\\', "\n" => '\n', "\t" => '\t', '/' => '\/',
            "\r" => '\r', "\b" => '\b', "\f" => '\f',
            '"' => '\"', chr(0x08) => '\b', chr(0x0C) => '\f'
        );
        $value = strtr($value, $replace);
        return '"' . $value . '"';
    } elseif (is_numeric($value)) {
        return $value;
    } elseif (is_bool($value)) {
        return $value ? 'true' : 'false';
    } elseif (empty($value)) {
        return '""';
    } else {
        return $value;
    }
}

/**
  +----------------------------------------------------------
 * 将一个字符串部分字符用*替代隐藏
  +----------------------------------------------------------
 * @param string    $string   待转换的字符串
 * @param int       $bengin   起始位置，从0开始计数，当$type=4时，表示左侧保留长度
 * @param int       $len      需要转换成*的字符个数，当$type=4时，表示右侧保留长度
 * @param int       $type     转换类型：0，从左向右隐藏；1，从右向左隐藏；2，从指定字符位置分割前由右向左隐藏；3，从指定字符位置分割后由左向右隐藏；4，保留首末指定字符串
 * @param string    $glue     分割符
  +----------------------------------------------------------
 * @return string   处理后的字符串
  +----------------------------------------------------------
 */
function hideStr($string, $bengin = 1, $len = 99, $type = 0, $glue = "@") {
    $string = trim($string);
    if (empty($string))
        return false;
    $array = array();
    if ($type == 0 || $type == 1 || $type == 4) {
        $strlen = $length = mb_strlen($string);
        while ($strlen) {
            $array[] = mb_substr($string, 0, 1, "utf8");
            $string = mb_substr($string, 1, $strlen, "utf8");
            $strlen = mb_strlen($string);
        }
    }
    switch ($type) {
        case 1: {
                $array = array_reverse($array);
                for ($i = $bengin; $i < ($bengin + $len); $i++) {
                    if (isset($array[$i]))
                        $array[$i] = "*";
                }
                $string = implode("", array_reverse($array));
            }
            break;
        case 2: {
                $array = explode($glue, $string);
                $array[0] = hideStr($array[0], $bengin, $len, 1);
                $string = implode($glue, $array);
            }
            break;
        case 3: {
                $array = explode($glue, $string);
                $array[1] = hideStr($array[1], $bengin, $len, 0);
                $string = implode($glue, $array);
            }
            break;
        case 4: {
                $left = $bengin;
                $right = $len;
                $tem = array();
                for ($i = 0; $i < ($length - $right); $i++) {
                    if (isset($array[$i]))
                        $tem[] = $i >= $left ? "*" : $array[$i];
                }
                $array = array_chunk(array_reverse($array), $right);
                $array = array_reverse($array[0]);
                for ($i = 0; $i < $right; $i++) {
                    $tem[] = $array[$i];
                }
                $string = implode("", $tem);
            }
            break;
        default: {
                for ($i = $bengin; $i < ($bengin + $len); $i++) {
                    if (isset($array[$i]))
                        $array[$i] = "*";
                }
                $string = implode("", $array);
            }
            break;
    }
    return $string;
}

//获取id地址
function getIP() {
    global $ip;
    if (getenv("HTTP_CLIENT_IP"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if (getenv("HTTP_X_FORWARDED_FOR"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (getenv("REMOTE_ADDR"))
        $ip = getenv("REMOTE_ADDR");
    else
        $ip = "Unknow";
    return $ip;
}

/**
 * 获得当前的域名
 *
 * @return  string
 */
function get_domain($ret_protocol = true) {
    /* 协议 */
    $protocol = (isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';

    /* 域名或IP地址 */
    if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
        $host = $_SERVER['HTTP_X_FORWARDED_HOST'];
    } elseif (isset($_SERVER['HTTP_HOST'])) {
        $host = $_SERVER['HTTP_HOST'];
    } else {
        /* 端口 */
        if (isset($_SERVER['SERVER_PORT'])) {
            $port = ':' . $_SERVER['SERVER_PORT'];

            if ((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol)) {
                $port = '';
            }
        } else {
            $port = '';
        }

        if (isset($_SERVER['SERVER_NAME'])) {
            $host = $_SERVER['SERVER_NAME'] . $port;
        } elseif (isset($_SERVER['SERVER_ADDR'])) {
            $host = $_SERVER['SERVER_ADDR'] . $port;
        }
    }
    if ($ret_protocol) {
        return $protocol . $host;
    } else {
        return $host;
    }
}

/**
 * 生成UUID编码
 */
function uuid(){
	$chars = md5(uniqid(time().mt_rand(), true));
	$uuid  = substr($chars,0,8) . '-';
	$uuid .= substr($chars,8,4) . '-';
	$uuid .= substr($chars,12,4) . '-';
	$uuid .= substr($chars,16,4) . '-';
	$uuid .= substr($chars,20,12);
	return $uuid;
}

/**
 * 去除数组中为空的元素(配合array_filter函数使用)
 * @param string $val
 * @return boolean
 */
function removeNull($val) {

	if($val === '' || $val == null) {
		return false;
	}
	return true;
}

/**
 * 将数组转化成对象
 * @param Object $object
 * @param array $data
 * @return Object
 */
function array2object($object, $data) {
	foreach ($data as $key=>$value) {
		$object->$key = $value;
	}

	return $object;
}

/**
 * 获取随机字符串
 * @param int $len
 * @return string
 */
function randString($len) {
	$chars = array(
		'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
	);
	$charsLen = count($chars) - 1;
	shuffle($chars);    // 将数组打乱
	$output = "";
	for ($i=0; $i<$len; $i++) {
		$output .= $chars[mt_rand(0, $charsLen)];
	}
	
	return $output;
}

/**
 * 构造SQL语句
 * @param string $table
 * @param array $param
 * @return string
 */
function mksql($table, $param = array(),$field = '*') {
	$sql = "select {$field} from {$table} where 1=1";
	foreach ($param as $key => $val) {
		$sql .= " and {$key} = '{$val}'";
	}

	return $sql;
}


/**
 * 整数安全处理，仅返回大于等于0的整数
 * 判断是否为数字
 *
 **/
function numeric(& $variint) {
	if (! isset ( $variint ))
		return 0;
	if (! is_numeric ( $variint ))
		return 0;
	//首字符0处理
	$str_len = strlen ( $variint );
	for($i = 0; $i < $str_len; $i ++) {
		if ($variint [$i] != '0')
			break;
	}
	if ($i > 0 && $variint > 0) {
		$variint = substr ( $variint, $i, $str_len );
		$str_len = strlen ( $variint );
	}

	//数字安全处理
	if ($str_len > 0) {
		if (! preg_match ( "/^[0-9]+$/", $variint )) {
			return 0;
		} else {
			$variint = substr ( $variint, 0, 10 );
			//兼容MYSQL中INT无符号最大值4294967295
			$variint = ($variint > 4294967295) ? 4294967295 : $variint;
			return $variint;
		}
	} else {
		return 0;
	}
}

/**
 * 字符按个数截断，默认UTF8编码
 * */
function cutstr($str, $length, $dot = '...', $charset = 'utf-8') {
    if (mb_strlen ( $str ) <= $length)
        return $str;
    else {
        return mb_substr ( $str, 0, $length, $charset ) . $dot;
    }
}

/**
 * 格式化价格
 */
function price_format($price, $price_format = NULL) {
    if (empty($price))
        $price = '0.00';
    $price = number_format($price, 2 , '.' , '');

    if ($price_format === NULL) {
        $price_format = "￥%s";
    }

    return sprintf($price_format, $price);
}

/**
 * @param $var
 * 格式化array()或者object
 */
function pr($var) {
	$template = php_sapi_name() !== 'cli' ? '<pre>%s</pre>' : "\n%s\n";
	printf($template, print_r($var, true));
}


/**
 * curl方式，向指定的地址发送一个curl命令，以POST的方式
 * 注意，本方法没有设定太多的安全判断
 * @param string $url 访问的URL地址
 * @param array $posts POST的数据
 * @param boolean $return 是否返回
 * */
function sent_demand_curl($url, $posts, $return = FALSE, $https = false) {

    //open connection
    $ch = curl_init();
    //set the url, number of POST vars, POST data
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, "http://".setDefault($_SERVER , 'SERVER_NAME'));
    curl_setopt($ch, CURLOPT_POST, count($posts)); // 启用时会发送一个常规的POST请求，类型为：application/x-www-form-urlencoded，就像表单提交的一样。
    curl_setopt($ch, CURLOPT_POSTFIELDS, $posts); // 在HTTP中的"POST"操作。如果要传送一个文件，需要一个@开头的文件名
    if ($https) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
    $result = null;
    if ($return === true) {
        try {
            @ob_get_clean();
            @ob_start();
        } catch (Exception $e) {

        }

        curl_exec($ch);
        $result = ob_get_contents();

        try {
            @ob_end_clean();
        } catch (Exception $e) {

        }
    } else {
        curl_exec($ch);
    }
    //close connection
    curl_close($ch);
    return $result;
}

/**
	 * 发送一个curl请求
	 * @param string $url 请求的地址
	 * @param array $data 请求的数据 如果数据不为空则为POST请求 为空则为GET请求
	 * @param int $time default 30 超时时间
	 * @param bool $https default false 是否以Https协议发出请求
	 * @param string $referer 是否需要构造 Header中的referer
	 * @return string $result
	 */
	function CURLRequest( $url , $data , $time = 30 , $https = false , $referer = null ) {
		if (!function_exists('curl_init')) {
			die('SysTem need curl surport !!!');
		}
	    $ch = curl_init();
	    //设置请求源
	    curl_setopt($ch, CURLOPT_URL, $url);
	    //如果有需要伪造referer 则设置
	    if($referer) {
	    	curl_setopt($ch, CURLOPT_REFERER, $referer);
	    }
		//初始化数据 如果data不为空则为post请求
		if($data) {
			curl_setopt($ch, CURLOPT_POST, count($data));
	    	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $time);
		//是否需要按https 请求发送
	    if ($https) {
	        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	    }
	    $result = curl_exec($ch);
	    //close connection
	    curl_close($ch);
	    return $result;
	}

/** 
 * 截取URL中某个参数
 * beckzhang
 */
function clear_urlcan($url,$name){
	$rstr='';$re = array();
	$tmparr=parse_url($url);

	$rstr=empty($tmparr['scheme'])?'http://':$tmparr['scheme'].'://';
	$a = $_GET;
	unset($a[$name]);
	$rstr.=DOMAIN.$tmparr['path'].'?'.http_build_query($a);
	return $rstr;
}


/**
 +----------------------------------------------------------
 * 生成随机字符串
 +----------------------------------------------------------
 * @param int       $length  要生成的随机字符串长度
 * @param string    $type    随机码类型：0，数字+大小写字母；1，数字；2，小写字母；3，大写字母；4，特殊字符；-1，数字+大小写字母+特殊字符
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function randCode($length = 6, $type = 2) {
	$arr = array(1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&*(){}[]|");
	if ($type == 0) {
		array_pop($arr);
		$string = implode("", $arr);
	} elseif ($type == "-1") {
		$string = implode("", $arr);
	} else {
		$string = $arr[$type];
	}
	$count = strlen($string) - 1;
	$code = '';
	for ($i = 0; $i < $length; $i++) {
		$code .= $string[rand(0, $count)];
	}
	return $code;
}
/** 验证码是否正确 **/
function _checkMobileValicode($mobile, $code) {
	$flag = false;
	$sessionCode = Yii::app()->memcache->get($mobile . '_codecheck');
	if (trim($sessionCode) == trim($code)) { //验证通过
		$flag = true;
	}
	return $flag;
}

/**       -----------------    以下方法具有特殊性    --------------------------  */

/**
 * 外部方法获取SQL返回
 * @author beckzhang  此方法仅限用于YII框架中
 */
function query_sql($sql,$db="db"){
    $return = array();
    try {
        $re = Yii::app()->$db->createCommand($sql);
        $return = $re->queryall();
        return $return;
    }catch (Exception $e) {
        echo $e;
        Yii::log( $e->__toString(), CLogger::LEVEL_ERROR, __CLASS__.'::'.__METHOD__.'('.$e->getLine().')' );
    }
}


/**
 * 发送短信到手机
 * @param string $mobile
 * @param string $content
 */
function send2Mobile($mobile, $content) {
	
	$mess = new Cscmess();
	$mess->_postmass(array($mobile), $content);
	$mess->_getResponse();
}

function xml_to_array( $xml )
{
	$reg = "/<(\\w+)[^>]*?>([\\x00-\\xFF]*?)<\\/\\1>/";
	if(preg_match_all($reg, $xml, $matches))
	{
		$count = count($matches[0]);
		$arr = array();
		for($i = 0; $i < $count; $i++)
		{
		$key= $matches[1][$i];
		$val = xml_to_array( $matches[2][$i] );  // 递归
		if(array_key_exists($key, $arr))
		{
		if(is_array($arr[$key]))
		{
		if(!array_key_exists(0,$arr[$key]))
		{
		$arr[$key] = array($arr[$key]);
		}
		}else{
		$arr[$key] = array($arr[$key]);
		}
		$arr[$key][] = $val;
		}else{
			$arr[$key] = $val;
		}
		}
		return $arr;
		}else{
		return $xml;
		}
		}